package com.miplus.ccrm.core.service.action;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.miplus.ccrm.common.CmdResVo;
import com.miplus.ccrm.common.EnumRCode;
import com.miplus.ccrm.common.JPubUtils;
import com.miplus.ccrm.common.ServiceException;
import com.miplus.ccrm.core.controller.vo.action.*;
import com.miplus.ccrm.core.controller.vo.conf.WfNextStepVo;
import com.miplus.ccrm.core.mapper.FiCreditcasesMapper;
import com.miplus.ccrm.core.pojo.*;
import com.miplus.ccrm.core.mapper.FiDeadMapper;
import com.miplus.ccrm.core.service.FiWorkFlowCase;
import com.miplus.ccrm.core.service.conf.MsgAlertsService;
import com.miplus.ccrm.core.service.collect.FiTaskService;
import com.miplus.ccrm.core.service.cust.ConCustomerService;
import com.miplus.ccrm.core.service.file.FiApplyAttService;
import com.miplus.ccrm.core.service.strategy.CpCalllistService;
import com.miplus.ccrm.core.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
* @author pc
* @description 针对表【fi_dead】的数据库操作Service实现
* @createDate 2024-04-11 20:58:17
*/
@Slf4j
@Service
public class FiDeadServiceImpl extends MPJBaseServiceImpl<FiDeadMapper, FiDead>
    implements FiDeadService{

    @Resource
    private FiTaskService fiTaskService;
    @Resource
    private CpCalllistService cpCalllistService;
    @Resource
    private FiWorkFlowCase fiWorkFlowCase;
    @Resource
    private ConCustomerService conCustomerService;
    @Resource
    private FiApplyAttService fiApplyAttService;
    @Resource
    private MsgAlertsService msgAlertsService;

    @Resource
    private FiCreditcasesMapper fiCreditcasesMapper;

    @Override
    public IPage<FiDeadResVo> fiDeadList(String $usrid, FiApplyReqVo paras)
    {
        return selectJoinListPage(new Page<>(paras.getPageNum(), paras.getPageSize()),
                FiDeadResVo.class,
                new MPJLambdaWrapper<FiDead>()
                        .selectAs("fun_getnames('FI.DEAD.STATUS',t.status)", FiDeadResVo::getStatusdsc)
                        .selectAs("fun_getnames('FI.DEAD.REASON',t.applyreason)", FiDeadResVo::getApplyreasondsc)
                        .selectAs("(select cl.wfid from cp_calllist cl where cl.clid=t.clid)", FiDeadResVo::getWfid)
                        .selectAs("(select tg.dsc from sys_tags tg where tg.id=t.deadtag)",FiDeadResVo::getDeadtagdsc)
                        .selectAs("fun_getgrpname(t.applyusr)",FiDeadResVo::getApplygrpname)
                        .selectAs("cu.custname",FiDeadResVo::getCustname)
                        .leftJoin(ConCustomer.class,"cu",ConCustomer::getCustomernumber,FiDead::getCustomernumber)
                        .selectAll(FiDead.class)
                        .apply("fc_hasApplyView(t.applynumber,'SYS_DEAD',t.applyusr,{0},t.status,t.confirmusr)>0",$usrid)
                        .apply(JPubUtils.IsNotEmpty(paras.getApplygrp()),"fc_hasUsrInGroup(t.applyusr,{0})>0",paras.getApplygrp())
                        .eq(JPubUtils.IsNotEmpty(paras.getFicaseid()), FiDead::getFicaseid,paras.getFicaseid())
                        .eq(JPubUtils.IsNotEmpty(paras.getStatus()),FiDead::getStatus,paras.getStatus())
                        .eq(JPubUtils.IsNotEmpty(paras.getApplyusr()),FiDead::getApplyusr,paras.getApplyusr())
                        .between(JPubUtils.IsNotEmpty(paras.getStartdt()),FiDead::getApplydt,JPubUtils.StringToDate(paras.getStartdt()),JPubUtils.StringToDate(paras.getEnddt()))
                        .orderByAsc(FiDead::getApplydt)
        );
    }

    public String getDeadTag(String tag)
    {
        if(JPubUtils.IsEmpty(tag)){
            return "DEAD";
        }
        return tag;
    }

    @Override
    @Transactional
    public CmdResVo fiDeadAdd(String $usrid, FiDeadAddVo paras)
    {
        FiCreditcases ficase=fiCreditcasesMapper.selectById(paras.getFicaseid());
        //1=待审核
        List<FiDead> fiDead=selectJoinList(FiDead.class,
                new MPJLambdaWrapper<FiDead>()
                        .eq(FiDead::getCustomernumber,ficase.getCustomernumber())
                        .in(FiDead::getStatus, EnumConfirmStatus.New.value,
                                EnumConfirmStatus.Pending.value,EnumConfirmStatus.Pass.value)
        );
        //此客户死亡标签已经在处理中或存在
        if(JPubUtils.IsNotEmpty(fiDead)){
            throw new ServiceException(EnumRCode.DataProcess.value, EnumRCode.DataProcess.name);
        }
        String clid=paras.getClid();
        if(JPubUtils.IsEmpty(clid)){
            clid="SYS_DEAD"; //此任务是系统配置任务，不能delete
        }
        String deadtag=getDeadTag(paras.getDeadtag());

        Integer wfid=cpCalllistService.getCalllistWfID(clid);

        //CAMPAIGN.CHANNEL=11留案
        int tasknumber=fiTaskService.addTask($usrid,clid,paras.getFicaseid(), EnumFiChannel.Dead.value);

        int ret=0;
        log.info("applyAdd:clid={},ficase={},tasknumber={},wfid={}",clid,paras.getFicaseid(),tasknumber,wfid);

        FiDead fi = new FiDead();
        fi.setClid(clid);
        fi.setCustomernumber(paras.getCustnumber());
        fi.setDeadtag(deadtag);
        fi.setApplyreason(paras.getApplyreason());
        fi.setFicaseid(paras.getFicaseid());
        fi.setApplydsc(paras.getApplydsc());
        fi.setTasknumber(tasknumber);
        fi.setStatus(EnumConfirmStatus.New.value); //新建
        fi.setApplydt(new Date());
        fi.setApplyusr($usrid);
        ret=baseMapper.insert(fi);

        int applynumber=fi.getApplynumber();

        fiApplyAttService.AddApplyFile(applynumber,EnumFiChannel.Dead.toString().toLowerCase(),paras.getUploadList());

        if(wfid>0){
            String status=fiWorkFlowCase.doCreate($usrid,wfid,applynumber,tasknumber);
            fi = new FiDead();
            fi.setApplynumber(applynumber);
            fi.setStatus(Integer.parseInt(status)); //处理中
            baseMapper.updateById(fi);
        }

        return new CmdResVo(ret,Integer.toString(applynumber));
    }

    @Override
    public CmdResVo fiDeadCancel(String $usrid, FiApplyCancelVo paras)
    {
        FiDead fi=baseMapper.selectById(paras.getApplynumber());
        if(JPubUtils.IsNotEmpty(fi.getTasknumber())){
            fiTaskService.updateStatus(fi.getTasknumber(),$usrid,"X");
        }
        else{
            log.warn("applyCancel:getTasknumber.isnull");
        }
        //2024-07-16
        String deadtag=getDeadTag(fi.getDeadtag());
        String custid=fi.getCustomernumber();

        Integer wfid=cpCalllistService.getCalllistWfID(fi.getClid());
        fiWorkFlowCase.doCancel($usrid,wfid,fi.getApplynumber());

        fi = new FiDead();
        fi.setApplynumber(paras.getApplynumber());
        fi.setStatus(EnumConfirmStatus.Cancel.value); //取消
        fi.setCancelusr($usrid);
        fi.setCanceldt(new Date());
        int ret=baseMapper.updateById(fi);

        conCustomerService.delTag(custid,deadtag);

        return new CmdResVo(ret,fi.getApplynumber().toString());
    }

    @Override
    public CmdResVo fiDeadConfirm(String $usrid, FiApplyConfirmVo paras)
    {
        boolean confirmend=true;
        String okstatus=paras.getActionid().toString();
        FiDead fiDead=baseMapper.selectById(paras.getApplynumber());

        if(JPubUtils.IsNotEmpty(paras.getCaseactid())){
            //需要走工作流
            WfNextStepVo wfNextStepVo=fiWorkFlowCase.doExec($usrid,paras.getCaseactid(),
                    paras.getActionid(),paras.getWfcaseid(),paras.getConfirmdsc()
            );
            okstatus=wfNextStepVo.getStatus();

            //可能有多级审核,3=审核全部完成
            if(!JPubUtils.IsEqual(wfNextStepVo.getType(), EnumWorkFlowStep.End.value)) {
                confirmend=false;
            }
        }
        else{
            Integer wfid=cpCalllistService.getCalllistWfID(fiDead.getClid());
            if(wfid==null||wfid==0){//不使用工作流,这种情况下okstatus就是字典ID，直接写审核结果
                log.info("fiDeadConfirm.nouse workflow：okstatus={}",okstatus);
            }
            else{//可能配置错误或网络引起的，2024-08-29
                log.warn("fiDeadConfirm.nofind wf caseactid.");
                throw new ServiceException(EnumRCode.WfDataErr.value, EnumRCode.WfDataErr.name);
            }
        }

        //单纯就是审批流程，结果后续操作就在这里写，如果有后续反馈的，在result里面写，比如外访
        if(JPubUtils.IsNotEmpty(fiDead.getTasknumber())&&confirmend) {
            if(JPubUtils.IsEqual(okstatus,EnumConfirmStatus.Pass.value)){//审核通过
                log.info("applyConfirm.Ok:custid={} addTag={}",
                        fiDead.getCustomernumber(),fiDead.getDeadtag()
                );
                conCustomerService.addTag(fiDead.getCustomernumber(),"SYS",fiDead.getDeadtag());
            }
            msgAlertsService.msgAlertAdd(EnumFiChannel.Dead,
                    fiDead.getApplyusr(),
                    $usrid, EnumUtil.ConfirmStatusName(okstatus)
            );
            fiTaskService.updateStatus(
                    fiDead.getTasknumber(),
                    $usrid,
                    fiWorkFlowCase.getPassStatus(okstatus)
            );
        }

        FiDead fi = new FiDead();
        fi.setApplynumber(paras.getApplynumber());
        fi.setStatus(Integer.parseInt(okstatus));
        fi.setConfirmusr($usrid);
        fi.setConfirmdt(new Date());
        fi.setConfirmdsc(paras.getConfirmdsc());
        int ret=baseMapper.updateById(fi);

        return new CmdResVo(ret,paras.getApplynumber().toString());
    }

    @Override
    @Transactional
    public CmdResVo fiDeadListAdd(String $usrid, DeadListAddVo paras)
    {
        int ret=0;
        for(String custid : paras.getCustnumberlist()){
            FiDead fiDead=selectJoinOne(FiDead.class,
                    new MPJLambdaWrapper<FiDead>()
                            .eq(FiDead::getCustomernumber,custid)
                            .in(FiDead::getStatus, EnumConfirmStatus.New.value,
                                    EnumConfirmStatus.Pending.value,EnumConfirmStatus.Pass.value)
            );
            if(fiDead!=null){
                if(fiDead.getStatus()==EnumConfirmStatus.Pass.value){
                    //已经存在，不需要在增加
                    log.info("fiDeadListAdd:hasexist {}",custid);
                    continue;
                }
                else{
                    log.info("fiDeadListAdd:hasexistPending {}",custid);
                    fiDead.setConfirmusr($usrid);
                    fiDead.setConfirmdt(new Date());
                    fiDead.setStatus(EnumConfirmStatus.Pass.value);
                    baseMapper.updateById(fiDead);

                    conCustomerService.addTag(custid,"SYS","DEAD");
                }
            }
            else{
                fiDead=new FiDead();
                fiDead.setCustomernumber(custid);
                fiDead.setApplyreason(paras.getReason());
                fiDead.setApplydt(new Date());
                fiDead.setApplyusr($usrid);
                fiDead.setClid("SYS_DEAD");
                fiDead.setConfirmusr($usrid);
                fiDead.setConfirmdt(new Date());
                fiDead.setStatus(EnumConfirmStatus.Pass.value);
                fiDead.setDeadtag("DEAD");
                baseMapper.insert(fiDead);
                conCustomerService.addTag(custid,"SYS","DEAD");
            }
            ret++;
        }

        return new CmdResVo(ret);
    }
}




